var userInfoModule = angular.module("userInfoModule", []);
userInfoModule.controller("helloController", ['$scope', function($scope) {
  const valueTypeOptions = {
		NUMBER: "0",
    STRING: "''",
    BOOL: 'Boolean',
		ARRAY: "[]",
		OBJ: "{}",
    CLASS: "Class",
    CLASSARRAY: "[] Class",
    KEYCLASSOBJ: "{ key: Class }"
  }

  $scope.greeting = {
    num: "10",
    text: 'UpperCase',
    url: 'http://wx.test.pniutong.com/sweepstakes/oauth',
    appid: 'wxac53f7a8525ae028',
    state: '',
    ip:'192.168.0.103',
    ratioX: 16,
    ratioY: 9,
    contentText: '',
    lists: [['']],
    buildList: [],
    model: {
			keys: Object.keys(valueTypeOptions),
      options: valueTypeOptions,
      name: 'Model',
      params: [{}]
    },
    modelCode: '',
    bookName: ""
  };

  $scope.$watch('greeting.text', function() {
    $scope.textToLowercace = ($scope.greeting.text || "").toLowerCase();
  })

  $scope.$watch('greeting.time', function() {
    const date = ($scope.greeting.time === "" || isNaN($scope.greeting.time)) ? new Date() : new Date(parseInt($scope.greeting.time));
    $scope.localTimeString = date.toString();
    $scope.utcTimeString = date.toUTCString();
    // $scope.utcTimeString = moment(date).utc().format('MMM-D-YYYY HH:mm:ss A +UTC');
		$scope.timeMsString = date.getTime();
  })

  $scope.$watch('greeting.dataString', function() {
    const mdate = $scope.greeting.dataString ? moment.utc($scope.greeting.dataString, 'MMM-D-YYYY HH:mm:ss A +UTC') : moment();
    $scope.localTimeString = mdate.toDate().toString();
    $scope.utcTimeString = mdate.toDate().toUTCString();
    $scope.timeMsString = mdate.toDate().getTime();
  });

  $scope.result = eval($scope.greeting.num) / 40;
  $scope.$watch('greeting.num', function() {
    $scope.resultRem = eval($scope.greeting.num) / 40;
    $scope.result = eval($scope.greeting.num);
  });

  $scope.$watch('greeting.wsReqStr', function() {
    var wsReqContent = $scope.greeting.wsReqStr;
    var reg = /^[^\[]+(\[.*\])[\r\n]*$/;
    if (reg.test(wsReqContent)) {
      var paramString = wsReqContent.match(reg)[1];
      var paramArr = eval(paramString);
      var params = []
      for (var i = 0; i < paramArr.length; i++) {
        try {
          let str = paramArr[i];
          if (/\+/.test(str)) {
            str = str.replace(/\+/g, '');
          }
          var param = decodeURIComponent(str);
          param = JSON.parse(param);
          params[i] = JSON.stringify(param, null, 2);
        } catch (e) {
          params[i] = paramArr[i]
        }
      }
      $scope.wsReqArr = params
    } else if (wsReqContent) {
      try {
        $scope.wsReqArr = [JSON.stringify(JSON.parse(wsReqContent), null, 2)]
      } catch (e) {
        try {
          $scope.wsReqArr = [eval(wsReqContent)]
        } catch (e) {
          try {
            if (/\+/.test(wsReqContent)) {
              wsReqContent = wsReqContent.replace(/\+/g, '')
            }
            var val = decodeURIComponent(wsReqContent);
            $scope.wsReqArr = [JSON.stringify(JSON.parse(val), null, 2)];
          } catch {
            $scope.wsReqArr = ['Not Support']
          }
        }
      }
    } else {
      $scope.wsReqArr = [welcome().join(' ')]
    }
  })

  function updateUrl() {
    $scope.resultUrl = 'https://open.weixin.qq.com/connect/oauth2/authorize'
      + '?appid=' + $scope.greeting.appid
      + '&redirect_uri='+encodeURIComponent($scope.greeting.url)
      + '&response_type=code'
      + '&scope=snsapi_userinfo'
      + '&state='+$scope.greeting.state
      + '#wechat_redirect';
  }

  $scope.$watch('greeting.url', updateUrl);
  $scope.$watch('greeting.state', updateUrl);

  $scope.$watch('greeting.XY', calc);
  $scope.$watch('greeting.ratioX', calc)
  $scope.$watch('greeting.ratioY', calc)

  function calc() {
    calcX();
    calcY();
  }

  function calcX() {
    $scope.xx = '' + parseFloat($scope.greeting.ratioX) * parseFloat($scope.greeting.XY) / parseFloat($scope.greeting.ratioY);
  }

  function calcY() {
    $scope.yy = '' + parseFloat($scope.greeting.ratioY) * parseFloat($scope.greeting.XY) / parseFloat($scope.greeting.ratioX);
  }

  $scope.$watch('greeting.contentText', function() {
    $scope.greeting.contentGBK = escape($scope.greeting.contentText);
    $scope.greeting.contentUTF8 = encodeURIComponent($scope.greeting.contentText);
  });

  $scope.$watch('greeting.contentGBK', function() {
    $scope.greeting.contentText = unescape($scope.greeting.contentGBK);
    $scope.greeting.contentUTF8 = encodeURIComponent($scope.greeting.contentText);
  });

  $scope.$watch('greeting.contentUTF8', function() {
    $scope.greeting.contentText = decodeURIComponent($scope.greeting.contentUTF8);
    $scope.greeting.contentGBK = escape($scope.greeting.contentText);
  });

  var storeHandler = LocalStore('angular-lists')

  $scope.buildList = function() {
    var rets = []
    var ret = []

    var lists = $scope.greeting.lists;

    if (storeHandler.get(0)) {
      storeHandler.update(0, lists)
    } else {
      storeHandler.add(lists)
    }

    var list0 = lists[0];
    for (var b = 0; b < list0.length; b++) {

      var list1 = lists[1]
      if (list1) {
        for (var c = 0; c < list1.length; c++) {

          var list2 = lists[2]
          if (list2) {
            for (var d = 0; d < list2.length; d++) {

              var list3 = lists[3]
              if (list3) {
                for (var e = 0; e < list3.length; e++) {

                  var list4 = lists[4]
                  if (list4) {
                    for (var f = 0; f < list4.length; f++) {
                      ret.push(list0[b])
                      ret.push(list1[c])
                      ret.push(list2[d])
                      ret.push(list3[e])
                      ret.push(list4[f])
                      rets.push(ret.join(','))
                      ret = []
                    }
                  } else {
                    ret.push(list0[b])
                    ret.push(list1[c])
                    ret.push(list2[d])
                    ret.push(list3[e])
                    rets.push(ret.join(','))
                    ret = []
                  }
                }
              } else {
                ret.push(list0[b])
                ret.push(list1[c])
                ret.push(list2[d])
                rets.push(ret.join(','))
                ret = []
              }
            }
          } else {
            ret.push(list0[b])
            ret.push(list1[c])
            rets.push(ret.join(','))
            ret = []
          }
        }
      } else {
        ret.push(list0[b])
        rets.push(ret.join(','))
        ret = []
      }
    }
    $scope.greeting.buildList = rets
  }

  $scope.deleteIndex = function(index, subIndex) {
    const lists = $scope.greeting.lists;
    let newLists = [];
    for (var i = 0; i < lists.length; i++) {
      newLists[i] = Array.prototype.slice.call(lists[i])
    }
    if (subIndex >= 0) {
      newLists[index].splice(subIndex, 1)
    } else {
      newLists.splice(index, 1);
    }
    $scope.greeting.lists = newLists;
  }

  $scope.recoverLists = function() {
    var storeLists = storeHandler.get(0)
    if (storeLists) {
      $scope.greeting.lists = storeLists
    }
  }

  $scope.$watch('greeting.model', function() {
    const model = $scope.greeting.model;
    const name = model.name;
    const params = model.params || [{}];
    let modelCode = 'class ' + name + ' {\n';
    for (var i = 0; i < params.length; i++) {
      const param = params[i];
      if (param.name) {
        switch (param.type) {
					case valueTypeOptions.NUMBER:
          case valueTypeOptions.STRING:
					case valueTypeOptions.ARRAY:
					case valueTypeOptions.OBJ:
            modelCode += `  ${param.name} = ${param.type};\n`;
            break;
          case valueTypeOptions.KEYCLASSOBJ:
            modelCode += `  ${param.name} = ${valueTypeOptions.OBJ};\n`;
            break;
          case valueTypeOptions.CLASSARRAY:
            modelCode += `  ${param.name} = ${valueTypeOptions.ARRAY};\n`;
            break;
          case valueTypeOptions.BOOL:
            modelCode += `  ${param.name} = false;\n`;
            break;
          case valueTypeOptions.CLASS:
            modelCode += `  ${param.name} = new ${valueTypeOptions.CLASS}();\n`;
            break
        }
      }
    }
    modelCode += '\n'
    modelCode += '  toServer() {\n';
    modelCode += '    let ret = {};\n';
    for (var i = 0; i < params.length; i++) {
      const param = params[i];
      if (param.name) {
        switch (param.type) {
					case valueTypeOptions.NUMBER:
          case valueTypeOptions.STRING:
            modelCode += `    this.${param.name} && (ret.${param.name} = this.${param.name});\n`;
            break;
          case valueTypeOptions.ARRAY:
            modelCode += `    !_.isEmpty(this.${param.name}) && (ret.${param.name} = this.${param.name});\n`;
            break;
          case valueTypeOptions.OBJ:
            modelCode += `    this.${param.name} && (ret.${param.name} = this.${param.name});\n`;
            break;
          case valueTypeOptions.KEYCLASSOBJ:
            modelCode += `    this.${param.name} && (ret.${param.name} = this.${param.name});\n`;
            break;
          case valueTypeOptions.CLASSARRAY:
            modelCode += `    !_.isEmpty(this.${param.name}) && (ret.${param.name} = _.map(this.${param.name}, item => item.toServer()));\n`;
            break;
          case valueTypeOptions.BOOL:
            modelCode += `    this.${param.name} !== undefined ? (ret.${param.name} = this.${param.name}) : null;\n`;
            break;
          case valueTypeOptions.CLASS:
            modelCode += `    this.${param.name} && (ret.${param.name} = this.${param.name}.toServer());\n`;
            break
        }
      }
    }
    modelCode += '    return ret;\n'
    modelCode += '  }\n';
    modelCode += '}\n\n';
    modelCode += name + '.parse = function(data) {\n';
    modelCode += '  if (_.isEmpty(data)) return null;\n';
    modelCode += '  let model = new ' + name + '();\n';
    for (var i = 0; i < params.length; i++) {
      const param = params[i];
      if (param.name) {
        switch (param.type) {
					case valueTypeOptions.NUMBER:
          case valueTypeOptions.STRING:
            modelCode += `  model.${param.name} = data.${param.name} || ${param.type};\n`;
            break;
          case valueTypeOptions.ARRAY:
            modelCode += `  model.${param.name} = _.map(data.${param.name}, Class.parse) || [];\n`;
            break;
          case valueTypeOptions.OBJ:
            modelCode += `  model.${param.name} = _.isEmpty(data.${param.name}) ? null : data.${param.name};\n`;
            break;
          case valueTypeOptions.KEYCLASSOBJ:
            modelCode += `  model.${param.name} = {};\n`
                       + `  _.each(data.${param.name}, (clazz, key) => {\n`
                       + `    model.${param.name}[key] = Class.parse(clazz);\n`
                       + `  })\n`;
            break;
          case valueTypeOptions.CLASSARRAY:
            modelCode += `  model.${param.name} = _.map(data.${param.name}, Class.parse) || [];\n`;
            break;
          case valueTypeOptions.BOOL:
            modelCode += `  model.${param.name} = data.${param.name} !== undefined ? data.${param.name} : undefined;\n`;
            break;
          case valueTypeOptions.CLASS:
            modelCode += `  model.${param.name} = Class.parse(data.${param.name});\n`;
            break
        }
      }
    }
    modelCode += '  return model;\n';
    modelCode += '}\n\n'
    modelCode += 'export default ' + name + '\n ';
    $scope.greeting.modelCode = modelCode
  }, true);

  $scope.$watch('greeting.pipeText', function() {
    const text = $scope.greeting.pipeText;

    try {
      const data = JSON.parse(text);
      var result = data.data.map(item => '* ' + item.DisplayName + ' ' + item.Type)
      $scope.greeting.pipeResult = result.join('\n')
    } catch (e) {
      
    }
  })
  
  function bookNameOtherReplace(bookName) {
    var newBookName = bookName
      .replace(/•/g, "·")
      .replace(/ *\( */g, '(')
      .replace(/ *\) */g, ')')
      .replace(/ *（ */g, '(')
      .replace(/ *） */g, ')');
    
    $scope.greeting.newBookName = newBookName;
  }
  
  $scope.$watch('greeting.bookName', function() {
    const bookName = $scope.greeting.bookName;
    var ret = bookName;
    var reg = /^ *\[ *([^\x00-\xff]*) *\] *(.*) *$/;
    if (reg.test(bookName)) {
      var match = reg.exec(bookName);
      if (match) {
        ret = `${match[2]}〔${match[1]}〕`;
      }
      return bookNameOtherReplace(ret);
    }
    
    reg = /^ *\( *([^\x00-\xff]*) *\) *(.*) *$/;
    if (reg.test(bookName)) {
      var match = reg.exec(bookName);
      if (match) {
        ret = `${match[2]}〔${match[1]}〕`;
      }
      return bookNameOtherReplace(ret);
    }
    
    reg = /^ *（ *([^\x00-\xff]*) *） *(.*) *$/;
    if (reg.test(bookName)) {
      var match = reg.exec(bookName);
      if (match) {
        ret = `${match[2]}〔${match[1]}〕`;
      }
      return bookNameOtherReplace(ret);
    }
    
    reg = /^ *［ *([^\x00-\xff]*) *］ *(.*) *$/;
    if (reg.test(bookName)) {
      var match = reg.exec(bookName);
      if (match) {
        ret = `${match[2]}〔${match[1]}〕`;
      }
      return bookNameOtherReplace(ret);
    }
    
    reg = /^ *【 *([^\x00-\xff]*) *】 *(.*) *$/;
    if (reg.test(bookName)) {
      var match = reg.exec(bookName);
      if (match) {
        ret = `${match[2]}〔${match[1]}〕`;
      }
      return bookNameOtherReplace(ret);
    }
    
    reg = /^ *(.*) *\( *([^\x00-\xff]*) *\) *$/;
    if (reg.test(bookName)) {
      var match = reg.exec(bookName);
      if (match) {
        ret = `${match[1]}〔${match[2]}〕`;
      }
      return bookNameOtherReplace(ret);
    }
    
    reg = /^ *(.*) *（ *([^\x00-\xff]*) *） *$/;
    if (reg.test(bookName)) {
      var match = reg.exec(bookName);
      if (match) {
        ret = `${match[1]}〔${match[2]}〕`;
      }
      return bookNameOtherReplace(ret);
    }
    
    return bookNameOtherReplace(ret);
  })

}]);

//周日为第一天
function getMonthWeek(date) {
  /*
    a = d = 当前日期
    b = 6 - week = 当前周的还有几天过完（不算今天）
    a + b 的和在除以7就是当天是当前月份的第几周
  */
  var week = date.getDay();
  var d = date.getDate();
  return Math.ceil((d + 6 - week) / 7);
};
//周日为第一天
function getYearWeek(date) {
  /*
    date1是当年第一天
    d是当前日期是今年第多少天
    用days + 当前年的第一天的周差距的和在除以7就是本年第几周
  */
  var date1 = new Date(date.getFullYear(), 0, 1);
  var week = date1.getDay();
  var days = parseInt((date.getTime() - date1.getTime()) / 86400000);
  return Math.ceil((days + week + 1) / 7);
};

function welcome() {
  var now = new Date(), year = now.getFullYear(), hour = now.getHours();
  var yearWeek = getYearWeek(now);
  var week = now.getDay()
  var weekStart = new Date(now.getTime() - week * 86400000);
  var weekEnd = new Date(now.getTime() + (6 - week) * 86400000);
  var ret = [
    '今天是' + year + '年第' + yearWeek + '周(' + ((weekStart.getMonth() + 1 + '.' + weekStart.getDate()) + '-' + (weekEnd.getMonth() + 1 + '.' + weekEnd.getDate())) + ');',
    (now.getMonth() + 1) + '月' + now.getDate() + '日,',
    '星期' + '日一二三四五六'.charAt(week) + ';',
    '现在是北京时间' + now.toTimeString().substring(0, 8)
  ]
  
  var str = ''

  if (hour < 6) {
    str = "凌晨好!"
  } else if (hour < 9) {
    str = "早上好!"
  } else if (hour < 12) {
    str = "上午好!"
  } else if (hour < 14) {
    str = "中午好!"
  } else if (hour < 17) {
    str = "下午好!"
  } else if (hour < 19) {
    str = "傍晚好!"
  } else if (hour < 22) {
    str = "晚上好!"
  } else {
    str = "夜里好!"
  }
  ret.unshift(str)
  return ret;
}